const url = 'https://api.coze.cn/open_api/v2/chat';
const headers = {
  'Authorization': 'Bearer pat_hVVgIOe1sIUsaYjVJeUBWJAv7C4QYYuSaZzg2IH7zCds2zJEKwzfrTrIYZMYaK58',
  'Content-Type': 'application/json',
  'Accept': '*/*',
  'Host': 'api.coze.cn',
  'Connection': 'keep-alive'
};


function buildBody(fileUrl: string) {
  return JSON.stringify({
    conversation_id: '123',
    bot_id: '7376846098797084698',
    user: '29032201862555',
    query: `${fileUrl}\n这个文档说了什么`,
    stream: false
  });
}

let myHandler = async function (event, context, callback, logger) {
  // console.log(Date.now())
  const start = Date.now()
  const { fileUrl, fileType } = event.body ? JSON.parse(event.body) : event

  const body = buildBody(fileUrl)
  // do something here

  const response = await fetch(url, {
    method: 'POST',
    headers: headers,
    body: body
  });

  if (!response.ok) {
    callback({
      code: 400,
      desc: "生成失败，请稍后重试",
    })
    return
  }

  const data: any = await response.json();

  const messages: any[] = data.messages

  const result = messages.filter((item) => item.type === 'answer')[0].content


  // console.lo
  // logger.info("data::", data)

  // logger.info("real time:", Date.now() - start)

  callback({
    code: 200,
    desc: "Success.",
    data: result
  });
};

export { myHandler };